package com.changgou.system.util;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.crypto.Data;
import java.util.Base64;
import java.util.Date;

//Jwt工具类
public class JwtUtil {

    public static final Long JWT_TTL = 3600000L;   //有效期

    public static final String JWT_KEY = "itcast";   //设置秘钥明文


    /**
     * @Description:    创建jwt
     * @Author:        wangqingsong
     * @param:           [id, subject, ttlMills]
     * @return:          java.lang.String
     * @CreateDate:     2020/11/21 15:46
     */
    public static String createJwt(String id, String subject, Long ttlMills) {

        long millis = System.currentTimeMillis();
        Date now = new Date(millis);

        if (ttlMills == null) {
            ttlMills = JwtUtil.JWT_TTL;
        }

        long expMolls = millis + ttlMills;
        Date expDate = new Date(expMolls);
        SecretKey key = generalKey();

        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuer("admin")
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key)
                .setExpiration(expDate);

        return jwtBuilder.compact();
    }


    public static SecretKey generalKey() {
        byte[] decode = Base64.getDecoder().decode(JwtUtil.JWT_KEY);

        SecretKey key = new SecretKeySpec(decode, 0, decode.length, "AES");

        return key;
    }

}
